package com.xd.study.activity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.xd.study.R;

/**
 * Created by DGF on 2015/4/30.
 */
public class SharedPreferencesActivity extends Activity {

    private EditText txtUserName;
    private EditText txtPassword;
    private CheckBox chkRememberUserName;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sharedpreferences);

        txtUserName = (EditText)this.findViewById(R.id.sharedpreferences_txt_username);
        txtPassword = (EditText)this.findViewById(R.id.sharedpreferences_txt_password);
        chkRememberUserName = (CheckBox)this.findViewById(R.id.sharedpreferences_chk_rememberUserName);
        Button btnLogin = (Button)this.findViewById(R.id.sharedpreferences_btn_login);
        Button btnCancel = (Button)this.findViewById(R.id.sharedpreferences_btn_cancel);

        sharedPreferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
        editor = sharedPreferences.edit();

        String userName = sharedPreferences.getString("username", "");
        if (userName == null){
            chkRememberUserName.setChecked(false);
        }else{
            txtUserName.setText(userName);
            chkRememberUserName.setChecked(true);
        }

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userName = txtUserName.getText().toString();
                String password = txtPassword.getText().toString();
                boolean bRememberUserName = chkRememberUserName.isChecked();

                if ("admin".equals(userName) && "123456".equals(password)) {
                    if (bRememberUserName) {
                        editor.putString("username", userName);
                        editor.commit();
                        Toast.makeText(SharedPreferencesActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    }else {
                        editor.remove("username");
                        editor.commit();
                    }
                }else{
                    Toast.makeText(SharedPreferencesActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}
